<template>
  <!-- 店铺列表 list-shop -->
  <div class="list-shop">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>店铺管理</el-breadcrumb-item>
      <el-breadcrumb-item>店铺列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <!-- 搜索与添加区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryshop.query"
          clearable
          @clear="getShopList">
          <el-button
          slot="append"
          icon="el-icon-search"
          @click="getShopList"
          clearable></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加店铺</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 店铺数量 -->
    <el-card>
      <div class="shop_total">
        <div class="total">
          店铺数量 : <span>{{count}} </span>
        </div>
        <div class="total_ev">
          共享店铺数量 : <span>{{count}}</span>
        </div>
        <div class="total_money">
          销售总额 : <span>{{count}}</span>
        </div>
      </div>
    </el-card>
    <!-- 店铺列表 -->
    <el-card>
      <el-table
      :data="shoplist"
      stripe
      style="width: 100%">
        <el-table-column
          prop="shop_id" label="编号"
          width="100" align="center">
        </el-table-column>
        <el-table-column
          prop="shop_name" label="名称"
          width="150" align="center">
        </el-table-column>
        <el-table-column prop="shop_address" width="150"
        label="地址" align="center">
        </el-table-column>
        <el-table-column prop="shop_phone" width="100"
        label="电话" align="center">
        </el-table-column>
        <el-table-column width="150" label="审核" align="center">
          <template #default="{row}">
            <el-popover
              placement="bottom"
              width="400"
              trigger="click">
              <el-radio-group v-model="radio" @change="getRadio(row)">
                <el-radio label="0">初始化</el-radio>
                <el-radio label="1">待审核</el-radio>
                <el-radio label="2">审核通过</el-radio>
                <el-radio label="3">审核拒绝</el-radio>
              </el-radio-group>
              <el-button type="primary" plain size="mini"
               slot="reference"
              @click="exmain(row)">
              {{status[state.indexOf(row.audit_state)]}}
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column width="150" label="图片" align="center">
          <template #default="{row}">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.shop_avatar">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="remark" width="150" label="备注" align="center">
        </el-table-column>
        <el-table-column
        label="操作" align="center">
          <template #default="{row}">
            <el-tooltip class="item" effect="dark" content="详情" placement="top">
              <el-button type="Success" icon="el-icon-document" size="mini"
              @click="$router.push({path:'/list-shop/shop-details',query: {id:row.shop_id}})"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="查看商品" placement="top">
              <el-button type="primary" icon="el-icon-data-line" size="mini"
              @click="$router.push({path:'/product-list',query:{id:row.shop_id}})"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="经营分析" placement="top">
              <el-button type="warning" icon="el-icon-s-marketing" size="mini"
              @click="$router.push('/list-shop/business-analysis')"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" placement="top"
             :content="row.state==='start'?'开启':'关闭'">
              <el-switch
                v-model="row.state"
                size="mini"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="start"
                inactive-value="stop"
                @change="switchRun(row)">
              </el-switch>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="removeUserById(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryshop.pageNum"
      :page-sizes="[2, 5, 10, 15]"
      :page-size="queryshop.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="count">
      </el-pagination>
    </el-card>

    <!-- 添加商铺的对话框 -->
    <el-dialog
    title="添加商铺"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="shopInfo" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="商铺名称" prop="shop_name">
          <el-input v-model="shopInfo.shop_name"></el-input>
        </el-form-item>
        <el-form-item label="商铺地址" prop="shop_address">
          <el-input v-model="shopInfo.shop_address"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="shop_phone">
          <el-input v-model="shopInfo.shop_phone"></el-input>
        </el-form-item>
        <el-form-item label="店铺图像">
          <!-- action="后台API地址" 表示图片要上传到的后台API地址 -->
          <!-- list-type,文件的呈现方式 -->
          <el-upload
          :action="shopInfo.shop_avatar"
          :on-preview="handlePreview" :file-list="shop_photos"
          :on-remove="handleRemove" list-type="picture"
          :headers="headerObj" :on-success="handleSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addShop">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 改变审核状态 -->

    <!-- 图片预览 -->
    <el-dialog
    title="图片预览"
    :visible.sync="previewVisible"
    width="50%">
      <img :src="previewPath" alt="" class="previewImg">
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'list-shop',
  data () {
    // 自定义校验规则 验证手机号
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      status: [
        '初始状态',
        '待审核',
        '审核通过',
        '审核拒绝'
      ],
      state: [
        'int',
        'apply',
        'pass',
        'refuse'
      ],
      radio: '',
      value: true,
      states: false,
      // 查询参数对象
      queryshop: {
        query: '',
        pageNum: 1,
        pageSize: 2
      },
      // 店铺列表
      shoplist: [],
      // 对话框显隐
      addDialogVisible: false,
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 店铺实拍图片
      shop_photos: [],
      // 图片存储
      uploadFile: null,
      // 预览图片
      previewPath: '',
      // 图片预览对话框
      previewVisible: false,
      //   添加商铺的所有数据
      count: 0,
      // 添加店铺信息
      shopInfo: {
        shop_name: '小猪飞侠',
        shop_address: '222',
        shop_phone: '17674656046',
        // 上传图片的URL地址
        shop_avatar: 'http://192.168.14.75:9090/api/shop-info'
      },

      //   添加表单的验证规则对象
      addFormRules: {
        shop_name: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
        ],
        shop_address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        shop_phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getShopList()
  },
  mounted () {

  },
  methods: {
    // 获取店铺列表
    async getShopList () {
      const { data: res } = await this.$http.get('shops', { params: this.queryshop })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取店铺列表失败')
      this.shoplist = res.data.rows
      this.count = res.data.count
    },
    // 监听添加商铺对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
    //   console.log(newSize)
      this.queryshop.pageSize = newSize
      this.getShopList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
    //   console.log(newPage)
      this.queryshop.pageNum = newPage
      this.getShopList()
    },
    // 处理图片预览效果
    handlePreview (file) {
      this.previewPath = file.url
      // 显示图片
      this.previewVisible = true
    },
    // switch开关
    async switchRun (row) {
      // console.log(row.state)
      const remark = '改变' // 必传参数
      const { data: res } = await this.$http.put(`shop/${row.shop_id}/${row.state}`, { remark: remark })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新用户状态失败')

      this.$message.success('更新用户状态成功')
    },
    // 处理移除图片的操作
    handleRemove (file) {
      console.log(file)
      // 1.获取将要删除的图片的临时路径
      const filePath = file.raw
      // 2.从pics数组中，找到这个图片对应的索引值
      const i = this.shop_photos.findIndex(x => x.uploadFile === filePath)
      // 3.调用数组的splice 方法，把图片信息对象， 从pics 数组中移除
      this.shop_photos.splice(i, 1)
    },
    // 监听图片上传成功的事件
    handleSuccess (res, file) {
      this.uploadFile = file.raw
    },
    // 点击按钮,添加新商铺
    addShop () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const formData = new FormData()
        formData.append('shop_avatar', this.uploadFile)
        Object.keys(this.shopInfo).forEach(key => {
          formData.append(key, this.shopInfo[key])
        })
        // 可以发起添加商铺的网络请求
        const { data: res } = await this.$http.post('shop-info', formData)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('添加商铺失败')

        this.$message.success('添加商铺成功')
        // 隐藏添加商铺的对话框
        this.addDialogVisible = false
        // 重新获取商铺列表数据
        this.getShopList()
      })
    },
    // radio选择框改变
    async getRadio (row) {
      console.log(this.state[this.radio - 0])
      const { data: res } = await this.$http.put(`shop-audit/${row.shop_id}`, {
        audit_state: this.state[this.radio - 0],
        audit_info: '审核信息'
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('修改审核失败')
      this.$message.success('修改审核成功')
      this.getShopList()
    },
    // 审核状态
    async exmain (row) {
      this.radio = String(this.state.indexOf(row.audit_state))
    },
    // 删除
    async removeUserById (row) {
      // 弹框询问用户是否删除数据
      const confirmRsults = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // console.log(confirmRsults)
      if (confirmRsults !== 'confirm') return this.$message.info('已取消删除')

      // console.log('确认删除')
      const { data: res } = await this.$http.delete(`shop/${row.shop_id}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')

      this.$message.success('删除用户成功')
      this.getShopList()
    }
  }
}
</script>

<style scoped lang="less">
.list-shop{
  min-width: 1300px;
.el-form-item{
  .el-button{
    width: 80px;
    margin-right: 20px;
  }
}
.shop_total{
  // margin-top: 10px;
  // margin-left: 10px;
  width: 60%;
  display: flex;
  >div{
    flex:1;
  }
}
.el-switch{
  margin: 0 7px;
}
.previewImg{
  width: 100%;
}}
</style>
